package com.xuan.yrmanage.service;


import com.alibaba.fastjson.JSON;
import com.xuan.yrmanage.common.exception.ExceptionCast;
import com.xuan.yrmanage.common.redis.RedisConstValue;
import com.xuan.yrmanage.common.redis.StringDateRedisUtils;
import com.xuan.yrmanage.common.response.CommonCode;
import com.xuan.yrmanage.common.response.QueryResult;
import com.xuan.yrmanage.common.response.ResponseResult;
import com.xuan.yrmanage.dao.MenuMapper;
import com.xuan.yrmanage.dao.PermissionMapper;
import com.xuan.yrmanage.dao.repository.MenuRepository;
import com.xuan.yrmanage.domain.Menu;
import com.xuan.yrmanage.domain.Permission;
import com.xuan.yrmanage.domain.response.MenuCode;
import com.xuan.yrmanage.domain.view.MenuView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * FileName: SysMenuService
 * Author:   xuan zongjun
 * Date:     2020/2/26 10:15
 * Description: 菜单服务层
 */

@Service
@Transactional
public class MenuService {
    private final Logger logger = LoggerFactory.getLogger( MenuService.class );

    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private StringDateRedisUtils stringDateRedisUtils;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuRepository menuRepository;


    /**
     * 添加
     *
     * @param menu
     * @return
     */
    public ResponseResult insertSysMenu(Menu menu, String permissionIds, Integer userId) {
        //现在菜单分两级
        if (menu == null) {
            //非法参数
            return new ResponseResult( CommonCode.INVALID_PARAM );
        }
        //判断菜单是否存在
        int count = menuMapper.findByName( menu.getName() );
        if (count > 0) {
            return new ResponseResult( MenuCode.MENU_EXISTS_NAME );
        }

        if (menu.getParentMenuId() == null || menu.getParentMenuId() ==0 ) {
            menu.setParentMenuId( null );
            menu.setLevel( 1 );
        } else {
            menu.setLevel( 2 );
        }

        menu.setIsDelete( 0 );
        menu.setCreateTime( new Date() );
        menu.setCreateBy( userId );
        menuMapper.insert( menu );

        //添加菜单和权限的对应关系
        if (permissionIds != null) {
            List<Integer> permissionList = JSON.parseArray( permissionIds, Integer.class );
            for (Integer permissionId : permissionList) {
                menuMapper.insertMenuPermission( menu.getId(), permissionId );
            }
        }
        //清空用户的缓存
        stringDateRedisUtils.deleteHashRedis( RedisConstValue.MENU_LIST,null );
        stringDateRedisUtils.deleteHashRedis( RedisConstValue.INTERFACE_ULR,null );
        return new ResponseResult( CommonCode.SUCCESS );
    }


    /**
     * 获取列表
     *
     * @param pageIndex
     * @param pageSize
     * @param queryString 名称查询
     * @return
     */
    public ResponseResult findAll(int pageIndex, int pageSize, String queryString) {
        if (pageIndex <= 0) pageIndex = 1;
        if (pageSize <= 0) pageSize = 10;

        List<Menu> list = menuMapper.findAll( pageIndex, pageSize, queryString );

        //获取菜单下的权限
        for (Menu menu : list) {
           List<Permission> permissionList =  menuMapper.findPermissionByMenuId(menu.getId());
           menu.setPermissionList( permissionList );
           //获取父级菜单的名称
            Integer parentMenuId = menu.getParentMenuId();
            if(parentMenuId!=null){
                Menu parentMenu = menuMapper.findById( parentMenuId );
                menu.setParentMenuName( parentMenu!=null?parentMenu.getName():"" );
            }

        }

        //获取总数
        int count = menuMapper.getCount( queryString );

        //设置集合和总数
        QueryResult<Menu> queryResult = new QueryResult<>();
        queryResult.setList( list );
        queryResult.setTotal( count );

        return new ResponseResult( CommonCode.SUCCESS, queryResult );
    }

    /**
     * 修改
     *
     * @param menuId
     * @param menu
     * @return
     */
    public ResponseResult updateSysMenu(Integer menuId, Menu menu, String permissionIds, Integer userId) {
        if (menu == null) {
            //非法参数
            ExceptionCast.cast( CommonCode.INVALID_PARAM );
        }
        Menu exits = menuMapper.findById( menuId );
        if (exits == null) {
            ExceptionCast.cast( MenuCode.MENU_NOT_EXIST );
        }
        //修改
        menu.setUpdateTime( new Date(  ) );
        menu.setUpdateBy( userId );
        menuMapper.update( menu );

        if (permissionIds != null) {
            //删除菜单和权限的关系
            menuMapper.deleteMenuPermission( menuId );
            //添加菜单和权限的关系
            List<Integer> permissionList = JSON.parseArray( permissionIds, Integer.class );
            for (Integer permissionId : permissionList) {
                menuMapper.insertMenuPermission( menuId, permissionId );
            }
        }
        //清空用户菜单和权限的缓存
        //清空用户的缓存
        stringDateRedisUtils.deleteHashRedis( RedisConstValue.MENU_LIST,null );
        stringDateRedisUtils.deleteHashRedis( RedisConstValue.INTERFACE_ULR,null );
        return new ResponseResult( CommonCode.SUCCESS );

    }

    /**
     * 删除
     *
     * @param menuId
     * @return
     */
    public ResponseResult deleteSysMenuById(Integer menuId) {
        Menu one = menuMapper.findById( menuId );
        if (one == null) {
            return new ResponseResult( MenuCode.MENU_NOT_EXIST );
        }
        //删除菜单
        menuMapper.delete( menuId );
        //删除菜单和权限的对应关系
        menuMapper.deleteMenuPermission( menuId );

        //清空用户菜单和权限的缓存
        //清空用户的缓存
        stringDateRedisUtils.deleteHashRedis( RedisConstValue.MENU_LIST,null );
        stringDateRedisUtils.deleteHashRedis( RedisConstValue.INTERFACE_ULR,null );

        return new ResponseResult( CommonCode.SUCCESS );

    }

    /**
     * 分层返回2级菜单
     * @return
     */
    public ResponseResult getAllByLevel() {
        List<Menu> menuViewList = menuRepository.getAllByLevel();
        List<Menu> appMenu = menuViewList.stream().filter( menu -> "app".equals( menu.getName() ) ).collect( Collectors.toList() );
        menuViewList.removeAll( appMenu );

        return new ResponseResult( CommonCode.SUCCESS,menuViewList );
    }


    /**
     * 分层返回所有的菜单
     * @return
     */
    public List<Menu> getMenuAllByLevel() {

        List<Menu> menuAll = menuRepository.getAllByLevel();
        for (Menu menu : menuAll) {
            for (Menu childMenu : menu.getChildMenuList()) {
                List<Permission> permissionList = menuMapper.findPermissionByMenuId( childMenu.getId() );
                childMenu.setPermissionList( permissionList );
            }
        }
        return  menuRepository.getAllByLevel();
    }




    /**
     * 根据菜单返回对应的角色
     * @param menuId
     * @return
     */
    public ResponseResult getPermissionByMenuId(Integer menuId) {
        List<Permission> permissionByMenuId = menuMapper.findPermissionByMenuId( menuId );
        return new ResponseResult( CommonCode.SUCCESS,permissionByMenuId );
    }

    /**
     * 获取所有1级菜单
     * @return
     */
    public ResponseResult getOneLevelMenu() {
        List<Menu> menuViewList = menuMapper.getOneLevelMenu();
        return new ResponseResult( CommonCode.SUCCESS,menuViewList );
    }
}
